/**
 * 用户引导服务
 * 为新用户提供操作指导和帮助
 */
class UserGuideService {
    constructor() {
        this.guides = {
            'datasource': {
                title: '数据源管理引导',
                steps: [
                    {
                        target: '.datasource-type',
                        title: '选择数据源类型',
                        content: '首先选择您要添加的数据源类型：数据库或Excel文件',
                        position: 'bottom'
                    },
                    {
                        target: '#addDatasourceModal input[placeholder="请输入数据源名称"]',
                        title: '填写基本信息',
                        content: '输入数据源名称和描述，帮助您识别不同的数据源',
                        position: 'bottom'
                    },
                    {
                        target: '#databaseConfig',
                        title: '配置数据库连接',
                        content: '填写数据库连接信息，包括主机、端口、用户名和密码',
                        position: 'bottom'
                    },
                    {
                        target: '.test-connection-btn',
                        title: '测试连接',
                        content: '在保存前先测试连接，确保配置信息正确',
                        position: 'left'
                    },
                    {
                        target: '.save-datasource-btn',
                        title: '保存数据源',
                        content: '确认配置无误后，点击保存按钮完成数据源创建',
                        position: 'top'
                    }
                ]
            }
        };
        this.currentGuide = null;
        this.currentStep = 0;
        this.overlay = null;
        this.highlight = null;
    }

    /**
     * 开始引导
     * @param {string} guideName - 引导名称
     */
    startGuide(guideName) {
        const guide = this.guides[guideName];
        if (!guide) {
            console.warn(`引导 ${guideName} 不存在`);
            return;
        }

        this.currentGuide = guide;
        this.currentStep = 0;
        this.createOverlay();
        this.showStep();
    }

    /**
     * 创建遮罩层
     */
    createOverlay() {
        this.overlay = document.createElement('div');
        this.overlay.className = 'fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300';
        this.overlay.id = 'guide-overlay';
        document.body.appendChild(this.overlay);

        this.highlight = document.createElement('div');
        this.highlight.className = 'absolute border-2 border-blue-500 bg-blue-100 bg-opacity-20 rounded-lg shadow-2xl z-50 transition-all duration-300';
        this.highlight.id = 'guide-highlight';
        document.body.appendChild(this.highlight);
    }

    /**
     * 显示当前步骤
     */
    showStep() {
        if (!this.currentGuide || this.currentStep >= this.currentGuide.steps.length) {
            this.endGuide();
            return;
        }

        const step = this.currentGuide.steps[this.currentStep];
        const target = document.querySelector(step.target);

        if (!target) {
            console.warn(`引导目标 ${step.target} 不存在，跳过此步骤`);
            this.nextStep();
            return;
        }

        // 高亮目标元素
        this.highlightElement(target);
        
        // 显示引导框
        this.showGuideBox(target, step);
    }

    /**
     * 高亮目标元素
     * @param {HTMLElement} target - 目标元素
     */
    highlightElement(target) {
        const rect = target.getBoundingClientRect();
        const padding = 10;

        this.highlight.style.display = 'block';
        this.highlight.style.left = `${rect.left - padding}px`;
        this.highlight.style.top = `${rect.top - padding}px`;
        this.highlight.style.width = `${rect.width + padding * 2}px`;
        this.highlight.style.height = `${rect.height + padding * 2}px`;
    }

    /**
     * 显示引导框
     * @param {HTMLElement} target - 目标元素
     * @param {Object} step - 步骤信息
     */
    showGuideBox(target, step) {
        // 移除旧的引导框
        const oldBox = document.getElementById('guide-box');
        if (oldBox) {
            oldBox.remove();
        }

        const box = document.createElement('div');
        box.id = 'guide-box';
        box.className = 'absolute bg-white rounded-lg shadow-xl p-6 z-50 max-w-sm';
        
        const rect = target.getBoundingClientRect();
        const boxPosition = this.calculateBoxPosition(rect, step.position);

        box.style.left = `${boxPosition.x}px`;
        box.style.top = `${boxPosition.y}px`;

        box.innerHTML = `
            <div class="flex items-center mb-3">
                <div class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white font-bold mr-3">
                    ${this.currentStep + 1}
                </div>
                <h3 class="text-lg font-semibold text-gray-800">${step.title}</h3>
            </div>
            <p class="text-gray-600 mb-4">${step.content}</p>
            <div class="flex justify-between items-center">
                <div class="text-sm text-gray-500">
                    ${this.currentStep + 1} / ${this.currentGuide.steps.length}
                </div>
                <div class="space-x-2">
                    <button onclick="userGuideService.skipGuide()" 
                            class="px-3 py-1 text-sm text-gray-600 hover:text-gray-800 transition">
                        跳过
                    </button>
                    <button onclick="userGuideService.prevStep()" 
                            class="px-3 py-1 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition ${this.currentStep === 0 ? 'opacity-50 cursor-not-allowed' : ''}"
                            ${this.currentStep === 0 ? 'disabled' : ''}>
                        上一步
                    </button>
                    <button onclick="userGuideService.nextStep()" 
                            class="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition">
                        ${this.currentStep === this.currentGuide.steps.length - 1 ? '完成' : '下一步'}
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(box);
    }

    /**
     * 计算引导框位置
     * @param {DOMRect} targetRect - 目标元素位置
     * @param {string} position - 位置偏好
     * @returns {Object} 计算后的位置
     */
    calculateBoxPosition(targetRect, position) {
        const boxWidth = 400; // 估计的引导框宽度
        const boxHeight = 200; // 估计的引导框高度
        const margin = 20;
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;

        let x, y;

        switch (position) {
            case 'top':
                x = targetRect.left + (targetRect.width - boxWidth) / 2;
                y = targetRect.top - boxHeight - margin;
                break;
            case 'bottom':
                x = targetRect.left + (targetRect.width - boxWidth) / 2;
                y = targetRect.bottom + margin;
                break;
            case 'left':
                x = targetRect.left - boxWidth - margin;
                y = targetRect.top + (targetRect.height - boxHeight) / 2;
                break;
            case 'right':
                x = targetRect.right + margin;
                y = targetRect.top + (targetRect.height - boxHeight) / 2;
                break;
            default:
                x = targetRect.right + margin;
                y = targetRect.top;
        }

        // 确保不超出视窗边界
        x = Math.max(margin, Math.min(x, viewportWidth - boxWidth - margin));
        y = Math.max(margin, Math.min(y, viewportHeight - boxHeight - margin));

        return { x, y };
    }

    /**
     * 下一步
     */
    nextStep() {
        this.currentStep++;
        this.showStep();
    }

    /**
     * 上一步
     */
    prevStep() {
        if (this.currentStep > 0) {
            this.currentStep--;
            this.showStep();
        }
    }

    /**
     * 跳过引导
     */
    skipGuide() {
        this.endGuide();
    }

    /**
     * 结束引导
     */
    endGuide() {
        // 清理遮罩层和高亮
        if (this.overlay) {
            this.overlay.remove();
        }
        if (this.highlight) {
            this.highlight.remove();
        }

        // 清理引导框
        const box = document.getElementById('guide-box');
        if (box) {
            box.remove();
        }

        // 显示完成提示
        if (window.NotificationService) {
            window.NotificationService.success('引导完成！您可以开始使用数据源管理功能了', 3000);
        }

        this.currentGuide = null;
        this.currentStep = 0;
    }

    /**
     * 显示帮助提示
     * @param {string} elementId - 元素ID
     * @param {string} message - 帮助消息
     */
    showHelpTooltip(elementId, message) {
        const element = document.getElementById(elementId);
        if (!element) return;

        // 创建帮助图标
        const helpIcon = document.createElement('span');
        helpIcon.className = 'ml-2 text-gray-400 hover:text-gray-600 cursor-help';
        helpIcon.innerHTML = '❓';
        helpIcon.title = message;

        element.appendChild(helpIcon);
    }

    /**
     * 检查是否是首次使用
     * @param {string} featureName - 功能名称
     * @returns {boolean} 是否首次使用
     */
    isFirstTime(featureName) {
        const key = `first_time_${featureName}`;
        const visited = localStorage.getItem(key);
        
        if (!visited) {
            localStorage.setItem(key, 'true');
            return true;
        }
        
        return false;
    }

    /**
     * 自动开始引导（如果是首次使用）
     * @param {string} guideName - 引导名称
     */
    autoStartGuide(guideName) {
        if (this.isFirstTime(guideName)) {
            // 延迟启动，确保页面完全加载
            setTimeout(() => {
                if (confirm(`是否需要${this.guides[guideName]?.title || '操作引导'}？`)) {
                    this.startGuide(guideName);
                }
            }, 1000);
        }
    }
}

// 导出为全局变量
window.UserGuideService = UserGuideService;
window.userGuideService = new UserGuideService();